package online.zhangwenzhe.common.requestInfo;

import online.zhangwenzhe.common.Environment;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;

public class Sequence {
    private AtomicLong id = new AtomicLong(0);
    private int lastMinute = 0;
    private long requestId = 0;
    private static Sequence singleton;

    private static Sequence getInstance() {
        if (singleton == null) {
            synchronized (Sequence.class) {
                if (singleton == null) {
                    singleton = new Sequence();
                }
            }
        }
        return singleton;
    }

    public static long get() {
        return getInstance().requestId;
    }

    public static void increment() {
        getInstance().incrementRequestId();
    }

    private synchronized void incrementRequestId() {
        LocalDateTime current = LocalDateTime.now();

        //每分钟计数清零
        if (lastMinute != current.getMinute()) {
            id.set(0);
            lastMinute = current.getMinute();
        }

        long sequence = id.incrementAndGet();
        long prefix = (current.getYear() * 10000000000L +
                current.getMonthValue() * 100000000L +
                current.getDayOfMonth() * 1000000L +
                current.getHour() * 10000L +
                current.getMinute() * 100L +
                Environment.getMachineCode()) * 10000L;

        requestId = prefix + sequence;
    }
}
